package com.mk.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.springboot.mapper.PlateMapper;
import com.mk.springboot.pojo.Plate;
import com.mk.springboot.until.PageFactory;
import com.mk.springboot.until.Result;
import com.mk.springboot.until.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class PlateController {
    @Autowired
    PlateMapper plateMapper;

    @RequestMapping("/plate/list")
    @ResponseBody
    public PageFactory list(HttpServletRequest httpServletRequest) {
        String keyword = httpServletRequest.getParameter("keyword");
        Integer start = Integer.parseInt(httpServletRequest.getParameter("start"));
        Integer size = Integer.parseInt(httpServletRequest.getParameter("length"));
        Integer current = start / size + 1;

        PageFactory pageFac = new PageFactory();
        IPage<Plate> page = new Page<>(current, size);

        QueryWrapper qw = new QueryWrapper<Plate>();
        if (keyword != null) {
            qw.like("name", keyword);
        }
        plateMapper.selectPage(page, qw);

        pageFac.setRecordsFiltered(page.getTotal());
        pageFac.setRecordsTotal(page.getTotal());
        pageFac.setData(page.getRecords());

        return pageFac;
    }

    @GetMapping("/plate/edit")
    public String edit(Model model, HttpServletRequest httpServletRequest) {
        String id = httpServletRequest.getParameter("id");
        Plate plate = plateMapper.selectById(Integer.parseInt(id));
        model.addAttribute("plate", plate);
        return "/plate/edit";
    }

    @PostMapping("/plate/edit")
    @ResponseBody
    public Result edit(Plate plate) {
        plateMapper.updateById(plate);
        return ResultUtil.success("成功修改板块: " + plate.getName() + " 信息!");
    }

    @PostMapping("/plate/add")
    @ResponseBody
    public Result add(Plate plate) {
        plateMapper.insert(plate);
        return ResultUtil.success("成功添加板块：" + plate.getName() + "信息!");
    }

    @GetMapping("/plate/del")
    @ResponseBody
    public Result del(HttpServletRequest httpServletRequest) {
        String id = httpServletRequest.getParameter("id");
        plateMapper.deleteById(Integer.parseInt(id));
        return ResultUtil.success("成功删除板块信息!");
    }
}
